package com.wsc.wsckeeper.activities;

import java.util.Random;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.wsc.wsckeeper.R;
import com.wsc.wsckeeper.activities.base.BaseActivity;
import com.wsc.wsckeeper.components.SCallback;
import com.wsc.wsckeeper.components.SpinerPicker;

public class PasswordGeneratorActivity extends BaseActivity {
	public static final String RESULT = "result";

	private Button generate;
	private Button get;
	private TextView password;
	private TextView hint;

	private Random random = new Random();

	private SpinerPicker spChars;
	private SpinerPicker spUpper;
	private SpinerPicker spLower;
	private SpinerPicker spNumbers;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_password_generator);
		super.onCreate(savedInstanceState);
	}

	@Override
	public void initComponents() {
		spChars = (SpinerPicker) findViewById(R.id.spCharsCase);
		spUpper = (SpinerPicker) findViewById(R.id.spUpperCase);
		spLower = (SpinerPicker) findViewById(R.id.spLowerCase);
		spNumbers = (SpinerPicker) findViewById(R.id.spNumbersCase);
		generate = (Button) findViewById(R.id.generate);
		get = (Button) findViewById(R.id.get);
		password = (TextView) findViewById(R.id.password);
		hint = (TextView) findViewById(R.id.hint);
	}

	@Override
	public void initValues() {
		spChars.addCallback(callback);
		spUpper.addCallback(callback);
		spLower.addCallback(callback);
		spNumbers.addCallback(callback);

		refreshData();

		getActionBar().setSubtitle(R.string.action_password);
	}

	@Override
	public void initListeners() {
		generate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				refreshData();
			}
		});
		get.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent();
				i.putExtra(RESULT, password.getText().toString());
				setResult(RESULT_OK, i);

				finish();
			}
		});
	}

	public void refreshData() {
		StringBuilder result = new StringBuilder();

		result.append(spChars.getValue()).append(spUpper.getValue()).append(spLower.getValue()).append(spNumbers.getValue());

		for (int i = 0; i < result.length(); i++) {
			int pOld = random.nextInt(result.length());
			int pNew = random.nextInt(result.length());
			char c = result.charAt(pOld);
			result.deleteCharAt(pOld);
			result.insert(pNew, c);
		}

		hint.setText("Total: " + result.length() + " symbols");
		password.setText(result.toString());
	}

	private SCallback callback = new SCallback() {

		@Override
		public void run(Object value) {
			refreshData();
		}
	};

}
